package cn.iocoder.yudao.module.project.controller.admin.websocket;

import java.util.List;
import java.util.Map;

import cn.hutool.extra.spring.SpringUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.project.controller.admin.internalcode.vo.InternalCodePageReqVO;
import cn.iocoder.yudao.module.project.controller.admin.internalcode.vo.InternalCodeWorkstationRespVO;
import cn.iocoder.yudao.module.project.service.internalcode.InternalCodeService;
import cn.iocoder.yudao.module.system.api.oauth2.OAuth2TokenApi;
import cn.iocoder.yudao.module.system.api.oauth2.dto.OAuth2AccessTokenCheckRespDTO;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import com.fasterxml.jackson.databind.ObjectMapper;

public class WebSocketController extends TextWebSocketHandler {

    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static int userCount = 0;

    /**
     * 建立连接成功后调用
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("用户连接成功！当前用户数量：" + ++userCount);
        System.out.println("用户ID：" + session.getId());
    }

    /**
     * 处理接收到的消息
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();

        try {
            // 解析JSON消息
            Message receivedMessage = objectMapper.readValue(payload, Message.class);

            OAuth2TokenApi oauth2TokenApi = SpringUtil.getBean(OAuth2TokenApi.class);

            OAuth2AccessTokenCheckRespDTO accessToken = oauth2TokenApi.checkAccessToken(receivedMessage.getToken());
            Long userId = accessToken.getUserId();

            InternalCodeService internalCodeService = SpringUtil.getBean(InternalCodeService.class);
            List<Map<String, Object>> list = internalCodeService.listCurrentUserWorkstationOrderInfo(receivedMessage.getDeptId(), receivedMessage.getCacheOrderCode(), userId);

            CommonResult<List<Map<String, Object>>> commonResult = CommonResult.success(list);
            receivedMessage.setCurrentUserWorkstationOrderInfo(commonResult);

            InternalCodePageReqVO pageReqVO = BeanUtils.toBean(receivedMessage, InternalCodePageReqVO.class);
            pageReqVO.setLoginUserId(userId);
            PageResult<InternalCodeWorkstationRespVO> pageResult = internalCodeService.listCurrentWorkstationDetail(pageReqVO);
            CommonResult<PageResult<InternalCodeWorkstationRespVO>> currentWorkstationDetail = CommonResult.success(pageResult);
            receivedMessage.setCurrentWorkstationDetail(currentWorkstationDetail);

            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(receivedMessage)));
            //session.sendMessage(new TextMessage("ssssss"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 连接关闭后调用
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {

    }

    /**
     * 处理传输错误
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.err.println("传输错误: " + exception.getMessage());
        session.close(CloseStatus.SERVER_ERROR);
    }

}
